[PHP] Does unsetting array values during iterating save on memory?
Posted
by
saturn_rising
on Stack Overflow
See other posts from Stack Overflow
or by saturn_rising
Published on 2011-01-12T21:16:38Z
Indexed on
2011/01/12
22:53 UTC
Read the original article
Hit count: 90
Hello fellow code warriors,
This is a simple programming question, coming from my lack of knowledge of how PHP handles array copying and unsetting during a foreach
loop. It's like this, I have an array that comes to me from an outside source formatted in a way I want to change. A simple example would be:
$myData = array('Key1' => array('value1', 'value2'));
But what I want would be something like:
$myData = array([0] => array('MyKey' => array('Key1' => array('value1', 'value2'))));
So I take the first $myData
and format it like the second $myData
. I'm totally fine with my formatting algorithm. My question lies in finding a way to conserve memory since these arrays might get a little unwieldy. So, during my foreach
loop I copy the current array value(s) into the new format, then I unset the value I'm working with from the original array. E.g.:
$formattedData = array();
foreach ($myData as $key => $val) {
// do some formatting here, copy to $reformattedVal
$formattedData[] = $reformattedVal;
unset($myData[$key]);
}
Is the call to unset()
a good idea here? I.e., does it conserve memory since I have copied the data and no longer need the original value? Or, does PHP automatically garbage collect the data since I don't reference it in any subsequent code?
The code runs fine, and so far my datasets have been too negligible in size to test for performance differences. I just don't know if I'm setting myself up for some weird bugs or CPU hits later on.
Thanks for any insights.
-sR
© Stack Overflow or respective owner